package com.xianyun.book.gatewayimpl.elasticsearch.repository.impl;

import com.xianyun.book.gatewayimpl.elasticsearch.dataobject.BookEsDO;
import com.xianyun.book.gatewayimpl.elasticsearch.repository.BookEsRepository;
import com.xianyun.book.gatewayimpl.elasticsearch.repository.base.BaseEsRepository;
import com.xianyun.book.gatewayimpl.elasticsearch.repository.base.EsSupportRepository;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author macos-zyj
 */
@Service
public class BookEsRepositoryImpl extends
        BaseEsRepository implements BookEsRepository {
    @Resource
    private ElasticsearchRestTemplate restTemplate;

    @Resource
    private EsSupportRepository supportRepository;

    @Override
    public void createBookIndex(String index) {

    }

    @Override
    public void deleteBookIndex(String index) {

    }

    @Override
    public void insertBook(String index, List<BookEsDO> list) {

    }

    @Override
    public void updateBook(String index, List<BookEsDO> list) {

    }

    @Override
    public void deleteBook(String index, BookEsDO bookEs) {

    }

    @Override
    public List<BookEsDO> searchBookList(String index) {
        return null;
    }

    @Override
    public List<BookEsDO> queryMatchList(String field, String value) {
        List<BookEsDO> resultList = new ArrayList<>();
        MatchQueryBuilder builder = QueryBuilders.matchQuery(field, value);
        NativeSearchQuery searchQuery = new NativeSearchQuery(builder);
        searchQuery.setMaxResults(300);
        SearchHits<BookEsDO> response =  restTemplate.search(searchQuery, BookEsDO.class);
        List<SearchHit<BookEsDO>> hitList = response.toList();
        if (hitList.size()>0){
            hitList.forEach(researchHit -> {
                        resultList.add(researchHit.getContent());
                    }
            );
        }
        return resultList;
    }

    @Override
    public List<String> searchBookSuggest(String searchKey) {
        return supportRepository.searchSuggest(searchKey);
    }
}
